package Res;

import org.json.*;

import Clock.Clock;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector3;
import Res.TextureMgr;

import java.io.Reader;
public class TileResource extends Resource 
{
	public TextureRegion[] res;
	public boolean bVis_ = true;
	public int nFrameNum;
	public int nTotalTime; // million second
	public int nCurFrame;
	// normally, we define the anchor as the center of a static image.
	public int nOffsetX = 0;
	public int nOffsetY = 0;
	
	private int nDuraPerFrame = 0;
 
	public TileResource()
	{
		nWidth = 0;
		nHeight = 0;
		nFrameNum = 0;	
		nCurFrame = 0;
	}
	
	public void LoadRes(String fileName)
	{
		FileHandle hFile = Gdx.files.internal(fileName);
		String data = hFile.readString();
		
		try
		{
			JSONObject json = new JSONObject(data);
			nWidth = json.getInt("w");
			nHeight = json.getInt("h");
			nFrameNum = json.getInt("fnum");
			nTotalTime = json.getInt("ttime");
			nOffsetX = json.getInt("offx");
			nOffsetY = json.getInt("offy");
			String texName = json.getString("file");			
			JSONArray idxs = json.getJSONArray("startpos");
			nDuraPerFrame = nTotalTime / nFrameNum;
			
			int sx = idxs.getInt(0);
			int sy = idxs.getInt(1);
			
			idxs = json.getJSONArray("endpos");
			
			int ex = idxs.getInt(0);
			int ey = idxs.getInt(1);
			
			Texture texture = TextureMgr.GetInst().GetTexture(texName);

			res = new TextureRegion[nFrameNum];
			
			int nFrameCnt = 0;
			for (int x = sx; x <= ex; x++) 
			{
				for (int y = sy; y <= ey; y++) 
				{
					res[nFrameCnt] = new TextureRegion(texture, x * nWidth, y * nHeight, nWidth, nHeight);
					nFrameCnt++;
				}
			}
		}
		catch(JSONException e)
		{
		
		}
		
	}
	
	public void LoadRes(JSONObject json)
	{
		
	}
	
	public void SetVisible(boolean bVis)
	{
		bVis_ = bVis;
	}
	
	public void Render(SpriteBatch spriteBatch, Matrix4 matrix)
	{
		TextureRegion resRender = res[nCurFrame];
		int width = resRender.getRegionWidth();
		if (width < 0) width = -width;
		
		int height = resRender.getRegionHeight();
		if (height < 0) height = -height;
		Matrix4 matrixOut = matrix.cpy();
		matrixOut.translate(-width / 2, -height/ 2, 0);
		matrixOut.translate(-nOffsetX, -nOffsetY, 0);


		spriteBatch.setTransformMatrix(matrixOut);
		spriteBatch.draw( resRender, 0, 0, width, height);
	}
	
	public void Update(Clock clock)
	{
		nCurFrame = clock.appTime / nDuraPerFrame % (nFrameNum - 1);
	}	
}
